
const https = require('https')
const SQLHelper = require('./SQLHelper')
const { formatTime } = require('./util')
//雪花算法生成id
const snowflake = require('./snowflake')


module.exports = function(app){
//登录拦截中间件
function loginRouter(req,res,next){
    let token =req.headers.token
    if(token){
        SQLHelper(`select * from session where id = ${token}`).then(ret =>{
            if(ret.length){
                let session =ret[0]
                req.session = {
                    userId:session.userId,
                    userName:session.userName
                }
                next()
            }
            else{
                res.status(406).send({errorMsg:'当前用户未登录'})
            }
        })


    }else{
        res.status(405).send({errorMsg:'缺少token,请先进行登录'})
    }

}


//让除了登录以外的所有小程序接口都先进行验证登录
app.use('/wx',loginRouter)

//微信登陆
app.get('/wxlogin',(req, res,next) => {
    let code = req.query.code
    let Appid='wxf331780ad7114ad2'
    let secret='ba53f4f49eb30beec8149ef8e7fe9bd3'
    https.get(`https://api.weixin.qq.com/sns/jscode2session?appid=${Appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`, (ret) => {
        ret.on('data', (ret) => {
    //         res.send(d.toString())

    //     });
    // }).on('error', (e) => {
    //         console.error(e);
    // }
    // );
            ret = JSON.parse(ret.toString())
            let openid = ret.openid
            if(!openid){
                res.send({errorMsg: ret.errMsg || '获取openid错误'})
            }
            else{
                //查询用户是否已经注册
                let queryMember = `select * from member where openId = '${openid}'`
                SQLHelper(queryMember).then(membersRet =>{
                    // console.log(membersRet)
                    if(membersRet.length){//用户已经存在
                         req.member = membersRet[0]
                        next()
                    }
            else{//用户不存在，使用openid注册用户
                        SQLHelper(`INSERT INTO member(openId) VALUES ('${openid}')`).then(newmember =>{
                            //注册成功返回新用户信息
                            SQLHelper(queryMember).then(newmember =>{
                                req.member = membersRet[0]
                                next()
                            })
                        })
                    }

                })
            }
        });
    
    }).on('error', (e) => {
            console.error(e);
            res.send({errorMsg:'获取openid错误'})
    });
},(req,res) =>{
    // let token = new Date().getTime()
    let token = snowflake()//token通过雪花算法获得
    let member = req.member
    //缓存到token到session表
    SQLHelper(`
    INSERT INTO session(id,userId,userName,inTime,platform) 
    VALUES ('${token}','${member._id}','${member.nickName}','${formatTime(new Date())}','wx')
    `).then(ret => {
    res.send({
    nickName:member.nickName,
    token,
    openId:member.openId,
    avatarUrl:member.avatarUrl,
    _id:member._id
    })
    })

    //缓存到token
    // tokens[token] = member
    // res.send({
    // nickName:member.nickName,
    // token,
    // openId:member.openId,
    // avatarUrl:member.avatarUrl,
    // _id:member._id
    // })

})


    //修改用户信息
    app.put('/wx/member',(req,res) =>{
        let userInfo = req.body
        console.log(userInfo,req.query)
        SQLHelper(`
        update member
        set nickName = '${userInfo.nickName}',avatarUrl='${userInfo.avatarUrl}'
        where _id = ${req.session.userId}
        `).then(ret =>{
            console.log(ret)
            res.send({})
        })

    })

    //获取收货地址列表
    //memberId 用户Id 必填
    app.get('/wx/address',loginRouter, (req,res) =>{
        if(req.session.userId){
            SQLHelper(`
            select * from address where state = 1 AND memberId = ${req.session.userId}
            `).then(ret => {
                res.send(ret)
            })
        }else{
            res.send({errorMsg:'请传入memberId'})
        }
    })

    //获取收货地址详情
    //addressId 地址_id 必填
    app.get('/wx/address/detail',(req,res) =>{
        if(req.query.addressId){
            SQLHelper(`
            select * from address where _id = '${req.query.addressId}'
            `).then(ret => {
                res.send(ret.length ? ret[0] : {errorMsg:'未获取地址详情'})
            })
        }else{
            res.send({errorMsg:'请传入addressId'})
        }
    })


        //新增收货地址
        //memberId 用户Id 必填
        //receiver 收货人 必填
        //phone 手机号 必填
        //city 省市区 必填
        //area 详细地址 非必填
        app.post('/wx/address',(req,res) => { 
            if (req.body.receiver && req.body.phone && req.body.city) {
                SQLHelper(`
                INSERT INTO address(memberId,receiver,phone,city,area,state) 
                VALUES ('${req.session.userId}','${req.body.receiver}','${req.body.phone}','${req.body.city}','${req.body.area || ''}',1)
                `).then(ret => {
                    // console.log(ret)
                    res.send(ret)
                })
            }else{
                res.send({errorMsg:'传入参数错误'})
            }
        })

        //修改已有的收货地址
        //addressId 地址Id 必填
        //receiver 收货人 非必填
        //phone 手机号 非必填
        //city 省市区 非必填
        //area 详细地址 非必填
        app.put('/wx/address',(req,res) => { 
            if (req.body.addressId) {
                let updateKey = ['receiver','phone','city','area']
                let updateValues = []
                for(let i=0;i<updateKey.length;i++){
                    let key = updateKey[i], value = req.body[key]
                    if(value) updateValues.push(`${key}='${value}'`)
                }
                SQLHelper(`UPDATE address set ${updateValues.join(',')} WHERE _id = ${req.body.addressId}`).then(ret => {
                    res.send(ret)
                })
            }else{
                res.send({errorMsg:'传入参数错误'})
            }
        })


//修改默认地址 必填
//addressId 主码_id 必填
 //memberId 用户_id  必填
 //isDefault 是否默认 非必填
app.put('/wx/address/default',(req,res) => {
    let addressId = req.body.addressId,memberId = req.session.userId,isDefault = req.body.isDefault
    if(addressId && memberId){
        if(isDefault == 1){//设置默认地址
            //取消其他默认地址
            SQLHelper(`
            UPDATE address
            set isDefault = 0
            WHERE isDefault =1 AND memberId = ${memberId}
            `).then(ret => {
                SQLHelper(`
                UPDATE address
                set isDefault = 1
                WHERE _id = ${addressId}
                `).then(ret => {
                    res.send(ret)
                })
            })
        }else{//取消默认地址
            SQLHelper(`
            UPDATE address
            set isDefault = 0
            WHERE _id = ${addressId}
            `).then(ret => {
                res.send(ret)
            })
        }
    }else{
        res.send({errorMsg:'传入参数错误'})
    }
})


//删除地址 逻辑删
//addressId 主码_id 必填
app.delete('/wx/address',(req,res) =>{
    let addressId = req.body.addressId
    if(addressId){
        SQLHelper(`
        UPDATE address
        set state = 0
        WHERE _id = ${addressId}
        `).then(ret =>{
            res.send(ret)
        })
    }else{
        res.send({errorMsg:'传入参数错误'})
    }
})

}